<template>
  <div>
    <el-form ref="form" :rules="rules" :model="formData" label-width="100px">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="设备属性设置" name="first">
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划名称" prop="name">
                <el-input v-model="formData.name" placeholder="计划名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="starttime">
                <el-date-picker
                  v-model="formData.starttime"
                  style="width:100%"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="轮灌选择" prop="serialno">
                <el-select v-model="formData.serialno" style="width:100%" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="(item,index) in devices"
                    :key="item.name + index"
                    :label="item.name + ' —— ' + item.serialno"
                    :value="item.serialno"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="水泵选择" prop="total_fee">
                <el-select v-model="formData.pump_serialno" style="width:100%" filterable clearable>
                  <el-option
                    v-for="(item,index) in pumps"
                    :key="item.name + index"
                    :label="item.name"
                    :value="item.serialno"
                  />
                </el-select></el-form-item>
            </el-col> -->
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="轮灌片区设置" name="second" :disabled="!formData.serialno">
          <el-row>
            <el-col :span="8">
              <el-radio-group v-model="ctl_type">
                <el-radio-button :label="1">系统轮灌组</el-radio-button>
                <el-radio-button :label="2">临时轮灌组</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="8" style="padding-right:6px;">
              <el-input v-model="setting.delay" type="number" placeholder="延时">
                <template slot="prepend">延时启动</template>
                <template slot="append">秒</template>
              </el-input>
            </el-col>
            <el-col :span="8" style="padding-left:6px;">
              <el-input v-model="setting.timetran" type="number" placeholder="延时">
                <template slot="prepend">运行时长</template>
                <template slot="append">分钟</template>
              </el-input>
            </el-col>
          </el-row>
          <div class="h12" />
          <el-table
            :data="cells"
            border
            style="width: 100%;margin-bottom:20px;"
            :row-key="getRowKey"
          >
            <el-table-column
              prop="idx"
              label="次序"
              align="center"
              type="index"
              width="60px"
            />
            <el-table-column
              prop="name"
              label="轮灌片区名称"
              align="center"
            >
              <template #default="scope">
                <el-tooltip class="item" effect="dark" :content="getValves(scope.row.devices)" placement="top">
                  <span>{{ scope.row.name }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="延时启动(秒)"
              align="center"
            >
              <template #header>
                <div class="flex">
                  <span>延时启动(秒)</span>
                  <el-tooltip class="item" effect="dark" content="可设置为负值，设置为负值时代表提前启动时间" placement="top">
                    <i class="el-icon el-icon-info" />
                  </el-tooltip>
                </div>
              </template>
              <template v-slot="scope">
                <el-input v-model="scope.row.delaySec" placeholder="延时启动" size="mini" type="number">
                  <template slot="append">秒</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="运行时长(分钟)"
              align="center"
            >
              <template v-slot="scope">
                <el-input v-model="scope.row.val" placeholder="运行时长" size="mini" type="number">
                  <template slot="append">分钟</template>
                </el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column
              prop="address"
              label="选择开口"
              align="center"
              width="160px"
            >
              <template v-slot="{row}">
                <el-radio-group v-model="row.port" size="mini">
                  <el-radio-button :label="1">1口开</el-radio-button>
                  <el-radio-button :label="2">2口开</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column> -->
            <el-table-column
              prop="address"
              label="操作"
              align="center"
              width="60px"
            >
              <template slot-scope="scope">
                <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="deleteRow(scope.row,scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-form-item :label-width="labelWidth">
        <el-button type="primary" @click="submit('form')">提交</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { dclassCodeMap } from '@/utils/constant'
import Sortable from 'sortablejs'
import { deepClone } from '@/utils'
export default {
  props: {
    formData: {
      type: Object,
      default() {
        return {
          name: '',
          starttime: '',
          isPumped: false,
          isCelled: false,
          pump: {}
        }
      }
    }
  },
  data() {
    return {
      setting: {
        delay: 30,
        timetran: 1
      },
      activeName: 'first',
      devices: this.$store.getters.devices.filter(val => {
        return +val.product_type === dclassCodeMap.dg
      }),
      pumps: this.$store.getters.devices.filter(val => {
        return +val.product_type === dclassCodeMap.sb
      }),
      rules: {
        name: [
          { required: true, message: '请输入计划名称', trigger: 'blur' }
        ],
        starttime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        serialno: [
          { required: true, message: '请选择设备', trigger: 'blur' }
        ]
      },
      cellsClone: [],
      cells: [],
      cellsSystem: [],
      cellsTemp: [],
      ctl_type: 1
    }
  },
  computed: {
    labelWidth() {
      return this.activeName === 'first' ? '100px' : '0'
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        if (newVal.serialno) {
          console.log(this.$store.getters.devicesObj[this.formData.serialno].cells)
          this.cellsClone = deepClone(this.$store.getters.devicesObj[this.formData.serialno].cells).map((val) => {
            val.val = this.setting.timetran
            val.delaySec = this.setting.delay
            return val
          })
        }
      },
      deep: true,
      immediate: true
    },
    ctl_type: {
      handler(newVal) {
        const cellsClone = deepClone(this.cellsClone)
        this.cells = cellsClone.filter((val) => {
          return +val.ctl_type === +newVal
        })
      },
      immediate: true
    },
    'setting.delay': {
      handler(newVal, oldVal) {
        if (newVal) {
          const cells = this.cells.map((val) => {
            val.delaySec = +newVal
            return val
          })
          this.cells = deepClone(cells)
        }
      },
      deep: true,
      immediate: true
    },
    'setting.timetran': {
      handler(newVal, oldVal) {
        if (newVal) {
          const cells = this.cells.map((val) => {
            val.val = +newVal
            return val
          })
          this.cells = deepClone(cells)
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
  // 阻止默认行为
    document.body.ondrop = (event) => {
      event.preventDefault()
      event.stopPropagation()
    }
    this.rowDrop()
  },
  methods: {
    getValves(valves) {
      const res = []
      valves.forEach((item) => {
        const name = item.rtu_serialno.substr(16, 4) + '-' + item.port
        res.push(name)
      })
      return res.join('，')
    },
    reset() {
      this.$emit('reset')
    },
    resetCells() {
      this.cells = this.$store.getters.devicesObj[this.formData.serialno].cells
      this.ctl_type = 1
      this.activeName = 'first'
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formData.cells = this.cells
          this.$emit('submit', this.formData)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleRateChange(row) {
      const rate = row.rate
      this.cells.map(item => {
        if (row.id === item.id) {
          return Object.assign(item, { rate: rate })
        }
      })
    },
    deleteRow(row, index) {
      this.cells.splice(index, 1)
    },
    addRow() {
      this.cells.push({
        serialno: '',
        name: 'a'
      })
    },
    getRowKey(row) {
      return row.idx
    },
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.cells.splice(oldIndex, 1)[0]
          _this.cells.splice(newIndex, 0, currRow)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.flex{
  align-items: center;
  justify-content: center;
}
.el-icon{
  font-size:16px;
  color:#F56C6C;
  margin-left:4px;
}
</style>
